from django.shortcuts import render
from django.views.decorators.http import *
from django.http import HttpResponse
from django.views.generic import View
from django.conf import settings
from django.http import HttpResponseRedirect
from kkoffer.user.models import company,job,member,message
from django.conf import settings
from django.http import JsonResponse

class dialogue(View):
    def get(self,request,id):
        context = {}
        uid = request.session['id']
        ids = message.objects.filter(to_id = uid).values('comeFrom')
        if request.session['type'] == 2:
            context['linkList'] = member.objects.filter(uid__in=ids)
        else:
            context['linkList'] = company.objects.filter(uid__in=ids)
        # import ipdb; ipdb.set_trace()
        if not ids:
            return render(request,'dialogue.html',context)
        id  = id or ids[0]['comeFrom']
        if id:
            context['id'] = id
            list1 = message.objects.filter(to = uid,comeFrom = id,type = 3)
            list2 = message.objects.filter(to = id,comeFrom =uid,type = 3)
            messageList = list1 | list2
            if request.session['type'] == 1:
                obj = company.objects.get(pk=id)
                # import ipdb; ipdb.set_trace()
                context['companyName'] = obj.name
            context['messageList'] = messageList.order_by('addTime')
        name = company.objects.filter(pk=id).values('name')
        name = company.objects.filter(pk=id).values('name')
        
        return render(request,'dialogue.html',context)
    def post(self,request,id):
        obj = message() 
        obj.content = request.POST.get('content')
        obj.to_id = request.POST.get('id')
        obj.comeFrom_id = request.session['id']
        obj.type = 3
        # obj.type = request.session['id']
        # import ipdb; ipdb.set_trace()
        obj.save()
        # return render(request,'dialogue.html',context)
        return HttpResponseRedirect('/dialogue/'+ request.POST.get('id'))

def memberDialogue(request,id):
    context = {}
    context['user'] = 1
    uid = request.session['id']
    ids = message.objects.filter(to_id = uid).values('comeFrom')
    context['linkList'] = company.objects.filter(uid__in=ids)
    company.objects.filter(uid__in=ids)
    if not ids:
        return render(request,'dialogue.html',context)
    id  = id or ids[0]['comeFrom']
    if id:
        context['id'] = id
        if request.session['type'] == 1:
            obj = company.objects.get(pk=id)
        list1 = message.objects.filter(comeFrom = id,type = 3)
        list2 = message.objects.filter(to = id,type = 3)
        messageList = list1 | list2
        context['messageList'] = messageList.order_by('addTime')
    return render(request,'dialogue.html',context)
